<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/25 0025
 * Time: 下午 3:06
 */

namespace app\index\controller;

use app\admin\model\User;
use app\index\model\IntegralUsed;
use think\Session;
use extend\Wxpay\Wechat;
use extend\Wxpay\WechatException;

class Sendpacket extends Common
{
    public function index()
    {
        $user = new User();
        $fee = input('get.num');
        $openid = $user::get(Session::get('userid'))->value('u_openid');
        if(empty($openid)){
            $this->error('请先绑定微信','Wechat/bindWechat');
        }else{
            $integral = integral(Session::get('userid'),2);
            if($fee > $integral){
                $this->error('积分不足');
            }else{
                $data['iu_uid'] = Session::get('userid');
                $data['iu_number'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                $data['iu_mean'] = 2;
                $data['iu_integral'] = $fee;
                $data['iu_type'] = input('get.type');
                $data['create_time'] = time();
                $insertid = (new IntegralUsed())->insertGetId($data);
                if($insertid){
                    $ret = array();
                    $wConf = v('wechat');
                    Wechat::setAppId($wConf['appid']);
                    Wechat::setAppSecret($wConf['appsecret']);
                    Wechat::setKey($wConf['key']);
                    Wechat::setMchId($wConf['mch_id']);
                    Wechat::setSslCertPath(realpath($wConf['ssl_cert']));//商户证书路径
                    Wechat::setSslKeyPath(realpath($wConf['ssl_key']));//商户证书路径
                    try {
                        $ret = Wechat::sendPacket($openid, $fee, '推广奖励', '护肤品', '护肤品推广');
                    }catch (WechatException $e){
                        $this->error('兑换红包出现错误，请联系客服反馈');
                    }
//                    (new IntegralUsed())->save(['iu_snumber' => $ret['send_listid'],'iu_status'=>1,'deal_time'=>time()],['id'=>$insertid]);
                    $data = ['id'=>$insertid,'iu_snumber' => $ret['send_listid'],'iu_status'=>1,'deal_time'=>time()];
                    $ret = $this->store(new IntegralUsed(),$data);
                    if($ret['status']=='success'){
                        $this->success('兑换成功');
                    }else{
                        $this->error('兑换失败');
                    }
                }
            }
        }
    }
}